package com.hy.study.utils;

import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author huyong
 * @date 2024 年 01 月 16 日 16:00: 57
 */
public class BasicFileUtil {
    public static InputStream getStreamByFileName(String fileName) throws IOException {
        if (fileName == null) {
            throw new IllegalArgumentException("fileName should not be null!");
        }
        if (fileName.startsWith("http")) {
            // 网络地址
            return new URL(fileName).openConnection().getInputStream();
        } else if (BasicFileUtil.isAbsFile(fileName)) {
            // 绝对路径
            Path path = Paths.get(fileName);
            return Files.newInputStream(path);
        } else if (fileName.startsWith("~")) {
            // 用户目录下的绝对路径文件
            fileName = BasicFileUtil.parseHomeDir2AbsDir(fileName);
            return Files.newInputStream(Paths.get(fileName));
        } else { // 相对路径
            return BasicFileUtil.class.getClassLoader().getResourceAsStream(fileName);
        }
    }

    /**
     * 将用户目录下地址~/xxx 转换为绝对地址
     *
     * @param path
     *
     * @return
     */
    public static String parseHomeDir2AbsDir(String path) {
        String homeDir = System.getProperties().getProperty("user.home");
        return StringUtils.replace(path, "~", homeDir);
    }

    public static boolean isAbsFile(String fileName) {
        if (OSUtil.isWinOS()) {
            // windows 操作系统时，绝对地址形如 c:\descktop
            return fileName.contains(":") || fileName.startsWith("\\");
        } else {
            // mac or linux
            return fileName.startsWith("/");
        }
    }

    @Test
    public void test2() throws IOException {
        String img = "https://c-ssl.duitang.com/uploads/item/201809/16/20180916175034_Gr2hk.thumb.1000_0.jpeg";
        BufferedImage pic = ImageIO.read(BasicFileUtil.getStreamByFileName(img));
        System.out.println(pic);
    }
}
